<template>
	<view class="show-pop" v-if="showpop">
		<view class="text-pop" @click="jumpTime">
			<view class="jump">
				跳过
			</view>
			<view class="time">
				{{time}}
			</view>
		</view>
		<cover-image
			src="/static/momo.jpeg"
			mode="aspectFit"
		></cover-image>
	</view>
	<up-sticky offset-top="0">
		<view class="p0">
			<view class="p1">
				<view :style="{height: top + 'px'}"></view>
				<view class="p2" :style="{height:height+'px'}">
					<view class="location" @click="onClickToMap">
						{{locationData.name}}
						<u-icon name="arrow-down-fill" size="10"></u-icon>
					</view>
					<view class="search">
						<u-search shape="round" actionText="" placeholder="搜索商家、活动" />
					</view>
				</view>
			</view>
			<view class="tabs">
				<u-tabs 
					:list="show_init_list" 
					@click="clickLabel" 
					lineColor="#fff"
					:scrollable="true"
					:activeStyle="{color: '#000', fontWeight: 'bold'}" :inactiveStyle="{color: '#8E8E8E' }"
					:itemStyle="{height: '88rpx'}">
					<!-- <template #right>
							<view style="margin-right: 40rpx" @tap="show_remain">
								<u-icon name="arrow-down" size="21" bold></u-icon>
							</view>
						</template> -->
				</u-tabs>
				<view v-if="show_remain_data.length" class="show_remain">
					<view v-for="(item, idx) in show_remain_data" :key="idx" class="show_remain_child" :style="{height: '60rpx'}">
						{{item.name}}
					</view>
				</view>
			</view>
		</view>
	</up-sticky>
	<!-- 瀑布 -->
	<view class="pubu" :style="{paddingBottom:'160rpx'}">
		<ShowIndex v-if="!listLoading && articleStore?.articleListData?.objects?.length && list.length"
			:dataList="articleStore.articleListData.objects" />
		<view v-else-if="!listLoading && Array.isArray(articleStore?.articleListData.objects)" class="empty-tip">
			暂无数据～
		</view>
		<view class="loading" v-show="list.length && articleStore?.articleListData?.objects?.length">
			{{scrollState ? '正在加载中...' : ''}}
		</view>
	</view>
	<TabBarVue type="home" />
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		nextTick,
		watch,
		watchEffect,
		getCurrentInstance,
		computed
	} from "vue"
	import {
		onShow,
		onLoad,
		onReachBottom
	} from "@dcloudio/uni-app"
	import QQMapWX from "@/libs/qqmap-wx-jssdk.js"
	import {
		MAP_KEY
	} from "@/config/config.ts"
	// import Waterfall from "@/components/Waterfall_old.vue"
	import ShowIndex from "@/components/ShowIndex.vue"
	import {
		height,
		top,
		bottom
	} from '@/utils/getMenuData'
	import {
		throttle
	} from '@/utils/throttle.ts'
	import {
		useShopStore,
		useLoginStore,
		useArticleStore
	} from '@/store'

	const shopStore = useShopStore()
	const loginStore = useLoginStore()
	const articleStore = useArticleStore()
	const deviceType = ref(null)
	const listLoading = ref(true)
	const locationData = reactive({
		name: "定位中...",
		longitude: null,
		latitude: null
	})
	const list = ref([])
	const pageData = reactive({
		pageNo: 1
	})
	const currentLabelName = ref('')

	// 获取城市
	/*  #ifdef  MP-WEIXIN  */
	const citySelector = requirePlugin('citySelector');
	// onShow(async () => {
	// 	const selectedCity = citySelector.getCity();
	// 	if (selectedCity) {
	// 		locationData.name = selectedCity?.name
	// 		locationData.longitude = selectedCity?.location?.longitude
	// 		locationData.latitude = selectedCity?.location?.latitude
	// 		uni.setStorageSync('locationData', {
	// 			...locationData
	// 		})
	// 	}
	// })
	//返回上一页时造成定位丢失,将本地存储的定位数据添加
	uni.onAppRoute(route => {
		const {
			name
		} = uni.getStorageSync("locationData")
		if (name) {
			locationData.name = name
		}
	});
	/* #endif */

	//单个tab的瀑布流数据
	let tabList = ref(list[0])
	// tab切换的动画控制
	const show = ref(true);
	// tab切换事件
	const tabClick = (item) => {
		tabList.value = list[item.index]
	}

	const onClickToMap = () => {
		if (alert) {
			return
		}
		let referer = 'aaa';
		const hotCitys = '北京,上海,天津,重庆,广州,深圳,成都,杭州'
		let endPoint = JSON.stringify({ //终点
			'name': '',
			'latitude': locationData.lat,
			'longitude': locationData.log,
		});
		wx.navigateTo({
			url: `plugin://citySelector/index?key=${MAP_KEY}&referer=${referer}&hotCitys=${hotCitys}`,
		})
	}

	//获取定位信息
	onShow(async () => {
		let res
		/*  #ifdef  MP-WEIXIN  */
		const selectedCity = citySelector.getCity();
		if (selectedCity) {
			locationData.name = selectedCity?.name
			locationData.longitude = selectedCity?.location?.longitude
			locationData.latitude = selectedCity?.location?.latitude
			res = {
				longitude: locationData.longitude,
				latitude: locationData.latitude
			}
			uni.setStorageSync('locationData', {
				...locationData
			})
		} 
		/*  #endif  */
			try {
				if(!res) {
					res = await uni.getLocation({
						type: 'wgs84',
					});
				}
			} catch (error) {
				uni.showToast({
					title: '定位获取异常'
				})
				locationData.name = '北京';
				res = {
					longitude: 116.29845,
					latitude: 39.95933
				}
			}
		/*  #ifdef  H5  */
		const h5LocaRes = await uni.request({
			url: `/ws/geocoder/v1/?location=${res?.latitude},${res?.longitude}&key=${MAP_KEY}`,
		})
		locationData.name = h5LocaRes?.data?.result?.ad_info?.city;
		/* #endif */
		/*  #ifdef  MP-WEIXIN  */
		const qqmapsdk = new QQMapWX({
			key: MAP_KEY
		});
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: res?.latitude,
				longitude: res?.longitude
			},
			success({
				result
			}) {
				locationData.name = result?.address_component?.city || '北京'
				uni.setStorageSync('locationData', {
					...locationData
				})
			},
			fail(error) {
				console.log("fail", error);
			}
		})
		/* #endif */
		locationData.latitude = res?.latitude
		locationData.longitude = res?.longitude
		await getArticleLabel()
		currentLabelName.value = list.value[0]?.name
		await getArticleData('init')
	})
	
	watchEffect(async () => {
		if (locationData.latitude && locationData.longitude) {
			await shopStore.shopLocation({
				latitude: locationData.latitude,
				longitude: locationData.longitude
			})
			await getArticleLabel()
			currentLabelName.value = list.value[0]?.name
			await getArticleData('init')
		}
	})

	async function getArticleData(init) {
		uni.showLoading({
			title: '列表数据加载中...'
		})
		if (init) {
			pageData.pageNo = 1
		}
		await articleStore.articleList({
			latitude: locationData.latitude,
			longitude: locationData.longitude,
			page: pageData.pageNo,
			pageSize: 10,
			source: 1,
			articleLabel: currentLabelName.value
		}, init)
		listLoading.value = false
		uni.hideLoading()
	}

	async function getArticleLabel() {
		const res = await articleStore.articleLabel({
			latitude: locationData.latitude,
			longitude: locationData.longitude,
			page: 1,
			pageSize: 100,
			source: 1
		})
		list.value = res?.data.map((item) => ({
			name: item
		}))
	}
	// 获取屏幕宽度
	const {
		windowWidth,
		windowHeight
	} = uni.getSystemInfoSync();
	// const show_tag_number = Math.ceil(windowWidth / 70)

	// 初始化用户列表展示
	const show_init_list = computed(() => {
		return list.value.slice(0)
	})

	let show_remain_data = ref([])
	// 剩余
	const show_remain = () => {
		if (show_remain_data.value.length === 0) {
			show_remain_data.value = list.value.slice(show_tag_number)
			return
		} else {
			show_remain_data.value = []
		}
	}
	const clickLabel = (item) => {
		currentLabelName.value = item.name
		getArticleData('init')
	}

	const scrollState = computed(() => {
		return pageData.pageNo < articleStore.articleListData.totalPage
	})

	onReachBottom(throttle(() => {
		if (scrollState) {
			pageData.pageNo++
			getArticleData()
		}
	}, 500))
	
	const time = ref(3)
	const timer = ref(null)
	const showpop = ref(true)
	timer.value = setInterval(() => {
		time.value = time.value-1
		if(time.value === 0) {
			showpop.value = false;
			clearInterval(timer.value)
		}
	}, 1000)
	
	const jumpTime = function () {
		showpop.value = false;
		clearInterval(timer.value)
	}
</script>
<style scoped lang="scss">
	.show-pop {
		width: 100vw;
		height: 100vh;
		position: fixed;
		left: 0;
		top: 0;
		background-color: #000;
		color: #fff;
		z-index: 99999;
	}
	.text-pop {
		position: absolute;
		display: flex;
		justify-content: space-around;
		top: 100rpx;
		left: 40rpx;
		background: #000;
		/* border: 1px solid #fff; */
		border-radius: 15px;
		width: 80px;
		height: 35px;
		line-height: 70rpx;
	}
	::-webkit-scrollbar {
		display: none;
	}

	.u-sticky {
		top: 0 !important;
	}

	.empty-tip {
		margin-top: 100rpx;
		text-align: center;
		color: #ccc;
	}

	.tabs {
		position: sticky;
		background-color: white;
	}

	.p0 {
		background-color: white;
	}

	.p2 {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-left: 20rpx;

		.location {
			display: flex;
			align-items: center;
			margin-right: 25rpx;
		}

		.search {
			max-width: 700rpx;
			min-width: 460rpx;
		}
	}

	.show_remain {
		display: flex;
		align-items: center;
	}

	.show_remain_child {
		margin-left: 20rpx;
		margin-right: 30rpx;
	}

	.loading {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
	}
</style>